// address.js - 路由模块
const Router = require('koa-router');
const jwt = require('jsonwebtoken');
const db = require('../db');
const router = new Router({ prefix: '/api/address' });
const { wx, jwtSecret, jwtExpire } = require('../config');


// 添加或修改地址（如果传 id 则为修改）
router.post('/save', async (ctx) => {
  const { id, name, phone, province_code, city_code, district_code, address, category, is_default } = ctx.request.body;
  const token = ctx.headers.authorization?.replace('Bearer ', '');
  const { userId } = jwt.verify(token, jwtSecret);
    console.log('~~~');
    
  if (is_default) {
    await db.query('UPDATE address SET is_default = 0 WHERE user_id = ?', [userId]);
  }

  if (id) {
    await db.query(
      `UPDATE address SET name=?, phone=?, province_code=?, city_code=?, district_code=?, address=?, category=?, is_default=? WHERE id=? AND user_id=?`,
      [name, phone, province_code, city_code, district_code, address, category, is_default || 0, id, userId]
    );
  } else {
    await db.query(
      `INSERT INTO address (user_id, name, phone, province_code, city_code, district_code, address, category, is_default) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [userId, name, phone, province_code, city_code, district_code, address, category, is_default || 0]
    );
  }

  ctx.body = { code: 200, message: id ? '修改成功' : '添加成功' };
});

// 获取地址列表
router.get('/list', async (ctx) => {
  const token = ctx.headers.authorization?.replace('Bearer ', '');
  const { userId } = jwt.verify(token, jwtSecret);
  const list = await db.query('SELECT * FROM address WHERE user_id = ? ORDER BY is_default DESC, created_at DESC', [userId]);
  ctx.body = { code: 200, data: list };
});

// 设置默认地址
router.post('/setDefault', async (ctx) => {
  const { id } = ctx.request.body;
  const token = ctx.headers.authorization?.replace('Bearer ', '');
  const { userId } = jwt.verify(token, jwtSecret);
  await db.query('UPDATE address SET is_default = 0 WHERE user_id = ?', [userId]);
  await db.query('UPDATE address SET is_default = 1 WHERE id = ? AND user_id = ?', [id, userId]);
  ctx.body = { code: 200, message: '设置成功' };
});

// 删除地址
router.post('/delete', async (ctx) => {
  const { id } = ctx.request.body;
  const token = ctx.headers.authorization?.replace('Bearer ', '');
  const { userId } = jwt.verify(token, jwtSecret);
  await db.query('DELETE FROM address WHERE id = ? AND user_id = ?', [id, userId]);
  ctx.body = { code: 200, message: '删除成功' };
});

module.exports = router;
